package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.CodeExceptionMessage;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * @author jingchun
 * @create 2024-07-05 14:54
 */

@Slf4j
@RestControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
public class ProductGlobalExceptionHandler {

	@ExceptionHandler(value = MethodArgumentNotValidException.class)
	public R handlerValidException(MethodArgumentNotValidException e) {
		e.printStackTrace();
		log.error("数据校验出现问题{}，异常类型{}",e.getMessage(),e.getClass());
		BindingResult bindingResult = e.getBindingResult();// 获取校验结果
		HashMap<Object, Object> map = new HashMap<>();
		bindingResult.getFieldErrors().stream().forEach(item -> {
			map.put(item.getField(),item.getDefaultMessage());
		});

		return R.error(CodeExceptionMessage.VALID_EXCEPTION.getCode(), CodeExceptionMessage.VALID_EXCEPTION.getMessage()).put("data",map);
	}

	@ExceptionHandler(value = Exception.class)
	public R handlerException(Exception e) {
		e.printStackTrace();
		log.error("错误信息：{}",e.getMessage());
		return R.error(CodeExceptionMessage.UNKNOWN_EXCEPTION.getCode(),
				CodeExceptionMessage.UNKNOWN_EXCEPTION.getMessage());
	}

}
